package com.cyh.nio;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 文件锁
 * */
public class FileLockDemo01 {

    public static void main(String[] args) throws Exception {
       String input = "atguigu";
        ByteBuffer buffer = ByteBuffer.wrap(input.getBytes());

        String filePath = "D:\\cyh\\work_java\\TestNioOrIo\\src\\com\\cyh\\5.txt";
        Path path = Paths.get(filePath);

        FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.APPEND);
        channel.position(channel.size() - 1);

        FileLock lock = channel.lock();
        //FileLock lock = channel.lock(0, Long.MAX_VALUE, true); //共享锁
        System.out.println("是否是共享锁：" + lock.isShared());

        channel.write(buffer);
        channel.close();

        readFile(filePath);
    }

    private static void readFile(String filePath) throws Exception{
        FileReader fileReader = new FileReader(filePath);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String tr = bufferedReader.readLine();
        while (tr != null) {
            System.out.println(" " + tr);
            tr = bufferedReader.readLine();
        }

        fileReader.close();
        bufferedReader.close();
    }
}
